/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmMain.java
 *
 * Created on 27.05.2011, 14:26:24
 */
package editor;

import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import jsyntaxpane.DefaultSyntaxKit;

import java.sql.Connection;
import java.sql.DriverManager;

import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;

import java.util.List;

/**
 *
 * @author Paul Kogel
 */
public class frmMain extends javax.swing.JFrame {

    /** Creates new form frmMain */
    public frmMain() {
        initComponents();
        
        DefaultSyntaxKit.initKit();        
        
        editor.setContentType("text/esql");   
        
        //compilerPath = "\"./lib/Compiler.jar\"";
        
        
        //center parent:        
        if(Toolkit.getDefaultToolkit().getScreenSize().width>this.getWidth())            
            this.setLocation(0 + (Toolkit.getDefaultToolkit().getScreenSize().width/2) - (this.getWidth()/2),this.getY());
        if(Toolkit.getDefaultToolkit().getScreenSize().height>this.getHeight())
            this.setLocation(this.getX(),0 + (Toolkit.getDefaultToolkit().getScreenSize().height/2) - (this.getHeight()/2));
    }
    
    //the file that is currentyl edited:
    private String file = "";
    
    //the location where the compiler.jar file is stored:
    private String compilerPath = "./lib/Compiler.jar";

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        chooser = new javax.swing.JFileChooser();
        mnuTools = new javax.swing.JToolBar();
        tbNew = new javax.swing.JButton();
        tbOpen = new javax.swing.JButton();
        tbSave = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        tbUndo = new javax.swing.JButton();
        tbRedo = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        tbCompile = new javax.swing.JButton();
        tbRun = new javax.swing.JButton();
        pnlStatus = new javax.swing.JPanel();
        lblStatusInfo = new javax.swing.JLabel();
        lblStatusPosition = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        editor = new javax.swing.JEditorPane();
        mnuMain = new javax.swing.JMenuBar();
        mnuFile = new javax.swing.JMenu();
        mnuNew = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JPopupMenu.Separator();
        mnuOpen = new javax.swing.JMenuItem();
        mnuImportSQL = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        mnuSave = new javax.swing.JMenuItem();
        mnuExit = new javax.swing.JMenuItem();
        mnuEdit = new javax.swing.JMenu();
        mnuUndo = new javax.swing.JMenuItem();
        mnuRedo = new javax.swing.JMenuItem();
        jSeparator5 = new javax.swing.JPopupMenu.Separator();
        mnuFind = new javax.swing.JMenuItem();
        mnuBuild = new javax.swing.JMenu();
        mnuCompile = new javax.swing.JMenuItem();
        mnuRun = new javax.swing.JMenuItem();
        mnuHelp = new javax.swing.JMenu();
        mnuOnline = new javax.swing.JMenuItem();
        jSeparator6 = new javax.swing.JPopupMenu.Separator();
        mnuAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Datapace Editor");

        mnuTools.setFloatable(false);
        mnuTools.setRollover(true);

        tbNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/newFile24.png"))); // NOI18N
        tbNew.setToolTipText("New File");
        tbNew.setFocusable(false);
        tbNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuNewActionPerformed(evt);
            }
        });
        mnuTools.add(tbNew);

        tbOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/openProject24.png"))); // NOI18N
        tbOpen.setToolTipText("Open File");
        tbOpen.setFocusable(false);
        tbOpen.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbOpen.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuOpenActionPerformed(evt);
            }
        });
        mnuTools.add(tbOpen);

        tbSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/save24.png"))); // NOI18N
        tbSave.setToolTipText("Save file");
        tbSave.setEnabled(false);
        tbSave.setFocusable(false);
        tbSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSaveActionPerformed(evt);
            }
        });
        mnuTools.add(tbSave);
        mnuTools.add(jSeparator1);

        tbUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/undo24.gif"))); // NOI18N
        tbUndo.setToolTipText("Undo");
        tbUndo.setEnabled(false);
        tbUndo.setFocusable(false);
        tbUndo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbUndo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbUndo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuUndoActionPerformed(evt);
            }
        });
        mnuTools.add(tbUndo);

        tbRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/redo24.gif"))); // NOI18N
        tbRedo.setToolTipText("Redo");
        tbRedo.setEnabled(false);
        tbRedo.setFocusable(false);
        tbRedo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbRedo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbRedo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRedoActionPerformed(evt);
            }
        });
        mnuTools.add(tbRedo);
        mnuTools.add(jSeparator2);

        tbCompile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/compileSingle24.png"))); // NOI18N
        tbCompile.setToolTipText("Compile into .sql");
        tbCompile.setEnabled(false);
        tbCompile.setFocusable(false);
        tbCompile.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbCompile.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbCompile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuCompileActionPerformed(evt);
            }
        });
        mnuTools.add(tbCompile);

        tbRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/runProject24.png"))); // NOI18N
        tbRun.setToolTipText("Execute on database");
        tbRun.setEnabled(false);
        tbRun.setFocusable(false);
        tbRun.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        tbRun.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        tbRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRunActionPerformed(evt);
            }
        });
        mnuTools.add(tbRun);

        pnlStatus.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 2, 5));
        pnlStatus.setLayout(new java.awt.BorderLayout());
        pnlStatus.add(lblStatusInfo, java.awt.BorderLayout.CENTER);
        pnlStatus.add(lblStatusPosition, java.awt.BorderLayout.EAST);

        editor.setEnabled(false);
        editor.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                editorCaretUpdate(evt);
            }
        });
        jScrollPane1.setViewportView(editor);

        mnuFile.setText("File");

        mnuNew.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        mnuNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/newFile (2).png"))); // NOI18N
        mnuNew.setText("New File");
        mnuNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuNewActionPerformed(evt);
            }
        });
        mnuFile.add(mnuNew);
        mnuFile.add(jSeparator4);

        mnuOpen.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        mnuOpen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/openProject.png"))); // NOI18N
        mnuOpen.setText("Open File");
        mnuOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuOpenActionPerformed(evt);
            }
        });
        mnuFile.add(mnuOpen);

        mnuImportSQL.setText("Import .sql");
        mnuImportSQL.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuImportSQLActionPerformed(evt);
            }
        });
        mnuFile.add(mnuImportSQL);
        mnuFile.add(jSeparator3);

        mnuSave.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        mnuSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/save.png"))); // NOI18N
        mnuSave.setText("Save");
        mnuSave.setEnabled(false);
        mnuSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuSaveActionPerformed(evt);
            }
        });
        mnuFile.add(mnuSave);

        mnuExit.setText("Exit");
        mnuExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuExitActionPerformed(evt);
            }
        });
        mnuFile.add(mnuExit);

        mnuMain.add(mnuFile);

        mnuEdit.setText("Edit");

        mnuUndo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK));
        mnuUndo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/undo.gif"))); // NOI18N
        mnuUndo.setText("Undo");
        mnuUndo.setEnabled(false);
        mnuUndo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuUndoActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuUndo);

        mnuRedo.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
        mnuRedo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/redo.gif"))); // NOI18N
        mnuRedo.setText("Redo");
        mnuRedo.setEnabled(false);
        mnuRedo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRedoActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuRedo);
        mnuEdit.add(jSeparator5);

        mnuFind.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK));
        mnuFind.setText("Find");
        mnuFind.setEnabled(false);
        mnuFind.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuFindActionPerformed(evt);
            }
        });
        mnuEdit.add(mnuFind);

        mnuMain.add(mnuEdit);

        mnuBuild.setText("Build");

        mnuCompile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/compileSingle.png"))); // NOI18N
        mnuCompile.setText("Compile into .sql");
        mnuCompile.setEnabled(false);
        mnuCompile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuCompileActionPerformed(evt);
            }
        });
        mnuBuild.add(mnuCompile);

        mnuRun.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F5, 0));
        mnuRun.setIcon(new javax.swing.ImageIcon(getClass().getResource("/editor/images/runProject.png"))); // NOI18N
        mnuRun.setText("Execute on database");
        mnuRun.setEnabled(false);
        mnuRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuRunActionPerformed(evt);
            }
        });
        mnuBuild.add(mnuRun);

        mnuMain.add(mnuBuild);

        mnuHelp.setText("Help");

        mnuOnline.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        mnuOnline.setText("Online documentation");
        mnuOnline.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuOnlineActionPerformed(evt);
            }
        });
        mnuHelp.add(mnuOnline);
        mnuHelp.add(jSeparator6);

        mnuAbout.setText("About");
        mnuAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuAboutActionPerformed(evt);
            }
        });
        mnuHelp.add(mnuAbout);

        mnuMain.add(mnuHelp);

        setJMenuBar(mnuMain);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(mnuTools, javax.swing.GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
            .addComponent(pnlStatus, javax.swing.GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 872, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(mnuTools, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 534, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void mnuOnlineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuOnlineActionPerformed
        try {
            //open the project´s language wiki page:
            String url = "http://code.google.com/p/easy-sql/wiki/Language_Specification";
            java.awt.Desktop.getDesktop().browse(java.net.URI.create(url));
        } catch (IOException ex) {}
    }//GEN-LAST:event_mnuOnlineActionPerformed

    private void mnuAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuAboutActionPerformed
        //show about window:       
        new frmAbout(this,true).setVisible(true);
    }//GEN-LAST:event_mnuAboutActionPerformed

    private void mnuNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuNewActionPerformed
       //TODO: if already file opened, suggest saving!
        saveFile();        
        
        //creates a new easy-sql file:        
        chooser.setSelectedFile(null);
        chooser.resetChoosableFileFilters();
        chooser.addChoosableFileFilter(new Esql_Filter());
        chooser.setAcceptAllFileFilterUsed(false);
        int returnVal = chooser.showSaveDialog(this);       
        
        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            if(chooser.getFileFilter().getDescription().equals("Datapace files"))
            {
                file = chooser.getSelectedFile().getPath() + ".esql";
            }
            else
            {
                file=chooser.getSelectedFile().getPath();
            }
            if(file != null)
            {         
                String skeleton = "database\n{";
                skeleton += "\n\tdatabase.entries";
                skeleton += "\n\t{";
                skeleton += "\n\t\t";
                skeleton += "\n\t}";
                
                skeleton += "\n\tdatabase.relations";
                skeleton += "\n\t{";
                skeleton += "\n\t\t";
                skeleton += "\n\t}";
                skeleton += "\n}";
                
                String nl = System.getProperty("line.separator");
                
                
                BufferedWriter out = null;
                try
                {
                     out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));                     
                     out.write(skeleton.replace("\n", nl));
                     out.close();

                     //load editor:
                     tbSave.setEnabled(true);
                     mnuSave.setEnabled(true);

                     tbUndo.setEnabled(true);
                     mnuUndo.setEnabled(true);

                     tbRedo.setEnabled(true);
                     mnuRedo.setEnabled(true);        
                     
                     mnuFind.setEnabled(true);

                     tbCompile.setEnabled(true);
                     mnuCompile.setEnabled(true);

                     tbRun.setEnabled(true);
                     mnuRun.setEnabled(true);

                     editor.setText(skeleton);
                     editor.setEnabled(true);
                }
                catch(FileNotFoundException err)
                {System.out.println("Datei nicht gefunden");
                }
                catch(IOException err)
                {
                    System.out.println("Schreibfehler!");
                }
            }
        }
    }//GEN-LAST:event_mnuNewActionPerformed

    private void mnuOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuOpenActionPerformed
        //if file opened, save this one:
        saveFile();
        chooser.setSelectedFile(null);
        chooser.resetChoosableFileFilters();
        chooser.addChoosableFileFilter(new Esql_Filter());
        chooser.setAcceptAllFileFilterUsed(false);
        int returnVal = chooser.showOpenDialog(this);

        String content = "";
        
        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            String f=chooser.getSelectedFile().getPath();

            if(f != null)
            {                                                
                BufferedReader in = null;

                try
                {
                    String line = null;
                    in = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
                    do
                    {
                        line = in.readLine();

                        if(line!=null)
                            content +=line + "\n";

                    }  while(line != null);

                    in.close();
                    
                    //load editor:
                    file = f;
                    
                     tbSave.setEnabled(true);
                     mnuSave.setEnabled(true);

                     tbUndo.setEnabled(true);
                     mnuUndo.setEnabled(true);

                     tbRedo.setEnabled(true);
                     mnuRedo.setEnabled(true);        

                     mnuFind.setEnabled(true);

                     tbCompile.setEnabled(true);
                     mnuCompile.setEnabled(true);

                     tbRun.setEnabled(true);
                     mnuRun.setEnabled(true);

                     editor.setText(content);
                     editor.setEnabled(true);     
                     editor.setCaretPosition(0);
                }
                catch(FileNotFoundException err)
                {System.out.println("File not found.");
                }
                catch(IOException err)
                {
                    System.out.println("Unknown error while reading file.");
                }                                        
            }
        }                
    }//GEN-LAST:event_mnuOpenActionPerformed

    private void mnuImportSQLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuImportSQLActionPerformed
        //TODO insert import file code here...

        //if file opened, save this one:
        saveFile();
        
        chooser.setSelectedFile(null);
        chooser.resetChoosableFileFilters();
        chooser.addChoosableFileFilter(new Sql_Filter());
        chooser.setAcceptAllFileFilterUsed(false);
        int returnVal = chooser.showOpenDialog(this);

        String content = "";

        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            String f=chooser.getSelectedFile().getPath();

            if(f != null)
            {
                //compile into .esql:
                String output = "";
                lblStatusInfo.setText("Importing...");
                String outputFile = f.substring(0,f.lastIndexOf(".")) + ".esql";

                try
                {
                    String line;
                    Process p = Runtime.getRuntime().exec("java -jar " + compilerPath + " -c " + "\"" + f + "\"" + " " + "\"" + outputFile +"\"");
                    p.waitFor();

                    BufferedReader input =
                            new BufferedReader(new InputStreamReader(p.getInputStream()));
                    while ((line = input.readLine()) != null) {
                        output+=line;
                    }
                    input.close();                                        
                } catch (Exception err) {
                    System.err.append("\n" +err.getMessage());
                }

                if(!(output.toLowerCase().contains("error")||(output.toLowerCase().contains("warning"))))
                {
                    file = outputFile;
                    
                    lblStatusInfo.setText("Importing succeeded.");
                                            
                    BufferedReader in = null;

                    try
                    {
                        String line = null;
                        in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                        do
                        {
                            line = in.readLine();

                            if(line!=null)
                                content +=line + "\n";

                        }  while(line != null);

                        in.close();
                    }
                    catch(FileNotFoundException err)
                    {System.out.println("File not found.");
                    }
                    catch(IOException err)
                    {
                        System.out.println("Unknown error while reading file.");
                    }

                    //load editor:
                     tbSave.setEnabled(true);
                     mnuSave.setEnabled(true);

                     tbUndo.setEnabled(true);
                     mnuUndo.setEnabled(true);

                     tbRedo.setEnabled(true);
                     mnuRedo.setEnabled(true);

                     mnuFind.setEnabled(true);

                     tbCompile.setEnabled(true);
                     mnuCompile.setEnabled(true);

                     tbRun.setEnabled(true);
                     mnuRun.setEnabled(true);

                     editor.setText(content);                     
                     editor.setEnabled(true);
                     editor.setCaretPosition(0);
                }
                else
                    lblStatusInfo.setText(output);              

            }
        }
    }//GEN-LAST:event_mnuImportSQLActionPerformed

    private void mnuSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuSaveActionPerformed
        saveFile();
    }//GEN-LAST:event_mnuSaveActionPerformed

    private void saveFile()
    {                
        if(!file.equals(""))
        {
            String nl = System.getProperty("line.separator");
            BufferedWriter out = null;

            try {
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
                out.write(editor.getText().replace("\n", nl));
                out.close();            
            } catch (FileNotFoundException err) {
                System.out.println("Not able to save file.");
            } catch (IOException err) {
                System.out.println("\nError while saving file.");
            }

            lblStatusInfo.setText("Saved.");
        }
    }
    
    private void mnuExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuExitActionPerformed
        //TODO check for changes...
        saveFile();
        System.exit(0);
    }//GEN-LAST:event_mnuExitActionPerformed

    private void mnuUndoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuUndoActionPerformed
        //TODO insert undo code here...      
        jsyntaxpane.actions.ActionUtils.getSyntaxDocument(editor).doUndo();
    }//GEN-LAST:event_mnuUndoActionPerformed

    private void mnuRedoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRedoActionPerformed
        //TODO insert redo code here...
        jsyntaxpane.actions.ActionUtils.getSyntaxDocument(editor).doRedo();
    }//GEN-LAST:event_mnuRedoActionPerformed

    private void mnuFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuFindActionPerformed
        //TODO insert find code here...                             
        (new jsyntaxpane.actions.gui.ReplaceDialog(editor, jsyntaxpane.actions.DocumentSearchData.getFromEditor(editor))).setVisible(true);
    }//GEN-LAST:event_mnuFindActionPerformed

    private void mnuCompileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuCompileActionPerformed
        //TODO insert build code here...      
        compileFile();                               
    }//GEN-LAST:event_mnuCompileActionPerformed

    private boolean compileFile()
    {
        saveFile();
        
        String output = "";
        lblStatusInfo.setText("Compiling...");
        String outputFile = file.substring(0,file.lastIndexOf(".")) + ".sql";

        try 
        {
            String line;                        
            Process p = Runtime.getRuntime().exec("java -jar " + compilerPath + " -c " + "\"" + file + "\"" + " " + "\"" + outputFile +"\"");                                        
            p.waitFor();


            BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                output+=line;
            }
            input.close();                       
        } catch (Exception err) {
            System.err.append("\n" +err.getMessage());
        }

        
        if(!(output.toLowerCase().contains("error")||(output.toLowerCase().contains("warning"))||(output.toLowerCase().contains("missing"))))
        {
            lblStatusInfo.setText("Compiling succeeded.");
            return true;
        }
        else
        {
            lblStatusInfo.setText(output);
            return false;
        }
    }
    
    private List<String> getSQL_fromFile(String file)
    {
        List<String> inptFileLines = new ArrayList();

        //contains whole content of sql-file in DECOMPILE-mode:
        String content = "";

        //Reads the input file and adds each line as new item in inptFileLines
        BufferedReader in = null;

        try {
            String line = null;
            in = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            do {
                line = in.readLine();
                if (line != null) {
                    line = line.trim();
                    if (line.length() > 0) 
                    {
                        //kill comments:
                        if (!line.startsWith("--")) 
                        {
                            content += line;
                        }                        
                    }
                }

            } while (line != null);

            in.close();
            
            if (content.length() > 0) {
                inptFileLines = Arrays.asList(content.split(";"));                    
            }                

        } catch (FileNotFoundException err) {
            System.out.append("Error: input file was not found for executing code.\n");
            System.exit(0);
        } catch (Exception err) {
            System.out.append(err + "\nCritical error: program returned an undefined issue.\n");
            System.exit(0);
        }
        
        return inptFileLines;
    }
    
    private void mnuRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRunActionPerformed
        //TODO insert execute on db code here...
        
        frmConnect dialConnect = new frmConnect(this,true);
        dialConnect.setVisible(true);
        
        if(!dialConnect.wasCanceled)
        {
            Statement statement = null; 
            Connection connect = null;
                        
            lblStatusInfo.setText("Connecting...");
            try                
            {                              
                //load mySQL driver:
                Class.forName("com.mysql.jdbc.Driver");
                                
                connect = DriverManager.getConnection("jdbc:mysql://"+dialConnect.path+"?"
                                                + "user=" + dialConnect.user+"&" + "password="+new String(dialConnect.password));                
                statement = connect.createStatement();
                
                //compile file:                                
                if(compileFile())
                {                                    
                    lblStatusInfo.setText("Receiving SQL commands...");
                    //read SQL commands fom compiled file:
                    String outputFile = file.substring(0,file.lastIndexOf(".")) + ".sql";                
                    List<String>cmds = getSQL_fromFile(outputFile);

                    lblStatusInfo.setText("Executing commands...");
                    //execute commands:                        
                    for(String s :cmds)
                    {                    
                        statement.execute(s);
                    }

                    lblStatusInfo.setText("Executing succeeded.");
                }
                else                
                    throw new Exception();
                
            }
            catch (Exception e)
            {
                System.out.append("\n" + e.getMessage());
                
                //get error message:
                if(lblStatusInfo.getText().equals("Connecting..."))
                    lblStatusInfo.setText("Failed to connect. Check path, user and password.");
                if(lblStatusInfo.getText().equals("Receiving SQL commands..."))
                    lblStatusInfo.setText("Failed to compile file.");
                if(lblStatusInfo.getText().equals("Executing commands..."))
                    lblStatusInfo.setText("Failed to execute code.");                                
            }
            finally
            {
                try
                {
                    statement.close();
                    connect.close();
                }catch(Exception ex){}
            }
            
        }
    }//GEN-LAST:event_mnuRunActionPerformed

    private void editorCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_editorCaretUpdate
       //sets the current position in info label in status bar:
        try {             
            int line = jsyntaxpane.actions.ActionUtils.getLineNumber(editor, editor.getCaretPosition());
            int column = jsyntaxpane.actions.ActionUtils.getColumnNumber(editor, editor.getCaretPosition());
            
            lblStatusPosition.setText(Integer.toString(line+1) + "|" + Integer.toString(column));
        } catch (BadLocationException ex) {
            lblStatusPosition.setText("");
        }
        
        
    }//GEN-LAST:event_editorCaretUpdate

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try
                {
                  //Tell the UIManager to use the platform look and feel
                  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }
                catch(Exception e)
                {
                  //Do nothing
                }
                
                
                
                new frmMain().setVisible(true);
                
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser chooser;
    private javax.swing.JEditorPane editor;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private javax.swing.JPopupMenu.Separator jSeparator4;
    private javax.swing.JPopupMenu.Separator jSeparator5;
    private javax.swing.JPopupMenu.Separator jSeparator6;
    private javax.swing.JLabel lblStatusInfo;
    private javax.swing.JLabel lblStatusPosition;
    private javax.swing.JMenuItem mnuAbout;
    private javax.swing.JMenu mnuBuild;
    private javax.swing.JMenuItem mnuCompile;
    private javax.swing.JMenu mnuEdit;
    private javax.swing.JMenuItem mnuExit;
    private javax.swing.JMenu mnuFile;
    private javax.swing.JMenuItem mnuFind;
    private javax.swing.JMenu mnuHelp;
    private javax.swing.JMenuItem mnuImportSQL;
    private javax.swing.JMenuBar mnuMain;
    private javax.swing.JMenuItem mnuNew;
    private javax.swing.JMenuItem mnuOnline;
    private javax.swing.JMenuItem mnuOpen;
    private javax.swing.JMenuItem mnuRedo;
    private javax.swing.JMenuItem mnuRun;
    private javax.swing.JMenuItem mnuSave;
    private javax.swing.JToolBar mnuTools;
    private javax.swing.JMenuItem mnuUndo;
    private javax.swing.JPanel pnlStatus;
    private javax.swing.JButton tbCompile;
    private javax.swing.JButton tbNew;
    private javax.swing.JButton tbOpen;
    private javax.swing.JButton tbRedo;
    private javax.swing.JButton tbRun;
    private javax.swing.JButton tbSave;
    private javax.swing.JButton tbUndo;
    // End of variables declaration//GEN-END:variables
}
